<style lang="less">
  .ivu-poptip-rel{
    width: 100%;
  }
</style>
<template>
  <div class="tem-div">
    <!--搜索-->
    <Card class="tem-card">
      <div class="search-item" :style="searchItemStyle">
        <Form ref="searchForm" label-position="right" inline :label-width="60" class="frm-search">
          <FormItem label="用户名">
            <i-input placeholder="用户名" v-model="searchData.username"></i-input>
          </FormItem>
          <FormItem label="姓名">
            <i-input placeholder="姓名" v-model="searchData.name"></i-input>
          </FormItem>
          <FormItem label="手机号">
            <i-input placeholder="手机号" v-model="searchData.phone" :maxlength="11"></i-input>
          </FormItem>
          <FormItem label="状态">
            <i-select placeholder="状态" v-model="searchData.status" readonly clearable>
              <i-option v-for="item in statusArray" :value="item.value" :key="item.value">{{item.label}}</i-option>
            </i-select>
          </FormItem>
        </Form>
      </div>
      <div class="search-btn">
          <hy-icon-btn @click="changeSearchDiv" :text="searchDiv?'收起更多':'展开更多'" :iconType="searchDiv?'chevron-up':'chevron-down'" iconSize="12"></hy-icon-btn>
          <Button type="primary" @click="search(1)" icon="search" :loading="searchListLoading">搜索</Button>
          <i class="search-i"></i>
          <!-- <Button class="search-btn-plus" type="ghost" v-btnAuth="{code: 'userAdd'}" icon="plus" @click="showModal('add')">新增</Button> -->
          <Button class="search-btn-plus" type="ghost" v-btnAuth="'userAdd'" icon="plus" @click="showModal('add')">新增</Button>
      </div>
    </Card>
    <!--按钮-->
    <!--<Card class="tem-card">
      <div style="text-align: left">
        <i-button v-btnAuth="{code: 'userAdd'}" @click="showModal('add')">新增</i-button>
         <i-button v-btnAuth="{code: 'userEdit'}" @click="showModal('modify','get')">编辑</i-button>
         <i-button v-btnAuth="{code: 'userDelete'}" @click="showModal('delete')">删除</i-button>
      </div>
    </Card>-->
    <!--表格-->
    <Card class="tem-card">
      <!--table部分-->
      <Table border :columns="columnsTitle" :loading="searchListLoading" :data="list" @on-selection-change="handleSelectionChange"></Table>
      <br>
      <!-- 分页 -->
      <Page :total="totalElement"
            :current="searchData.pageNum"
            size="small"
            show-elevator
            show-sizer
            show-total
            style="text-align: right;"
            @on-change="search"
            @on-page-size-change="pageSizeChange"
            :page-size-opts="pageSizeOpts"
      ></Page>
    </Card>
    <!--弹出框-->
    <Modal v-model="modalObj.addOrModify" :mask-closable="false">
      <p slot="header">
        <span>{{modalObj.title}}</span>
      </p>
      <div style="text-align:center">
        <Form ref="form" :model="modalFormData" :rules="ruleValidate" :label-width="80">
          <FormItem label="所属机构" prop="orgName">
            <Poptip placement="bottom" v-model="showPoptip" style="width: 100%;">
              <Input ref="pId" v-model="modalFormData.orgName" @on-focus="handlerFocus" placeholder="请选择所属机构"></Input>
              <div class="api" ref="tree" slot="content" style="text-align: left;">
                <Tree :data="orgTree" @on-select-change="handleSelectTree"></Tree>
              </div>
            </Poptip>
          </FormItem>
          <hy-form-item :form="modalFormData" :formRow="modalFormItem"></hy-form-item>
        </Form>
      </div>
      <div slot="footer">
        <i-button type="success" size="large" :loading="actionLoading" @click="addOrUp('form')">确定</i-button>
        <i-button size="large" @click="modalObj.addOrModify = false">取消</i-button>
      </div>
    </Modal>
    <!--修改密码弹出框-->
    <Modal v-model="upPwdModalShow" :mask-closable="false">
      <p slot="header">
        <span>修改密码</span>
      </p>
      <div style="text-align:center">
        <Form ref="upPwdForm" :model="upPwdFormData" :rules="ruleUpPwdValidate" :label-width="80">
          <hy-form-item :form="upPwdFormData" :formRow="upPwdFormItem"></hy-form-item>
        </Form>
      </div>
      <div slot="footer">
        <i-button type="success" size="large" :loading="actionLoading" @click="upPwd('upPwdForm')">确定</i-button>
        <i-button size="large" @click="upPwdModalShow = false">取消</i-button>
      </div>
    </Modal>
  </div>
</template>
<script>
  import fetch from './service';
  import roleService from '@/page/main/userManage/role/service';
  import orgService from '@/page/main/userManage/org/service';
  import list from '@/js/mixins/list';
  import HyFormItem from '@/components/common/formItem/formItem.vue';
  import HyDetail from '@/components/common/detail/detail.vue';

  export default {
    components: {
      HyDetail,
      HyFormItem
    },
    mixins: [list],
    data () {
      return {
        loading: false,
        // 查询条件
        searchObj: {
//          orgId: ''
        },
        modalObj: {
          title: '',
          addOrModify: false
        },
        upPwdModalShow: false,
        showPoptip: false,
        columnsTitle: [
          {
            key: 'username',
            title: '用户名',
            width: 120
          },
          {
            key: 'name',
            title: '姓名'
          },
          {
            key: 'phone',
            title: '手机号'
          },
          {
            key: 'email',
            title: '邮箱'
          },
          {
            title: '所属机构',
            key: 'orgName'
          },
          {
            key: 'status',
            title: '状态',
            render: (h, params) => {
              return this._filters.enableFlag(h, params, 'status');
            }
          },
          {
            title: '操作',
            key: 'action',
            width: 180,
            fixed: 'right',
            align: 'center',
            render: (h, params) => {
              return h('div', [
//                params.row.status === 1 ? this._hyTool.createButton(h, params, this.upPwdModal, '修改密码') : null,
//                 params.row.status === 1 ? this._hyTool.createButton(h, params, this.disable, '禁用') : null,
                this._hyTool.createIconBtn(h, params, this.editItem, '编辑', 'edit', 20, {color: '#2db7f5'}, 'userEdit'),
                params.row.status === 1 ? this._hyTool.createIconBtn(h, params, this.disableItem, '禁用', 'locked', '', {color: 'red'}, 'userLock') : null,
                params.row.status === 0 ? this._hyTool.createIconBtn(h, params, this.disableItem, '启用', 'unlocked', '', {color: '#2d8cf0'}, 'userLock') : null,
                this._hyTool.createIconBtn(h, params, this.deleteItem, '删除', 'trash-a', '', {color: 'red'}, 'userDelete')
              ]);
            }
          }
        ],
        statusArray: [
          {
            value: '1',
            label: '正常'
          },
          {
            value: '0',
            label: '停用'
          }
        ],
        modalFormData: {
          username: '',
          password: '',
          name: '',
          phone: '',
          email: '',
          roleIdList: [],
          orgId: '',
          orgName: '',
          status: 1
        },
        modalFormItem: [
          {
            key: 'username',
            title: '用户名',
            property: {
              disabled: false
            }
          },
          {
            key: 'password',
            title: '密码',
            property: {
              disabled: false
            }
          },
          {
            key: 'name',
            title: '姓名'
          },
          {
            key: 'phone',
            title: '手机号',
            maxlength: '11'
          },
          {
            key: 'email',
            title: '邮箱'
          },
          {
            key: 'roleIdList',
            title: '角色',
            type: 'select',
            style: 'text-align: left',
            array: [],
            property: {
              multiple: true
            }
          }
        ],
        ruleValidate: {
          username: [
            {required: true, message: '用户名不能为空', trigger: 'blur'},
            {max: 40, message: '用户名不能超过40个字符且不包含空格', trigger: 'blur'},
            {pattern: '^[a-zA-Z][a-zA-Z0-9_]*$', message: '字母开头，由字母数字下划线组成', trigger: 'blur'}
          ],
          password: [
            {required: true, message: '密码不能为空', trigger: 'blur'},
            {max: 20, message: '密码不能超过20个字符且不包含空格', trigger: 'blur'}
          ],
          name: [
            {required: true, message: '姓名不能为空', trigger: 'blur'}
          ],
          phone: [
            {required: true, message: '手机号不能为空', trigger: 'blur'},
            {pattern: '^(13[0-9]|14[0-9]|15[0-9]|17[0-9]|18[0-9])\\d{8}$', message: '手机号格式不正确', trigger: 'blur'}
          ],
          email: [
            {pattern: '^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\\.[a-zA-Z0-9_-]{2,3}){1,2})$', message: '邮箱格式不正确', trigger: 'blur'}
          ],
          status: [
            {required: true, type: 'number', message: '性别不能为空', trigger: 'blur change'}
          ],
          orgName: [
            {required: true, message: '所属机构不能为空', trigger: 'blur'}
          ]
        },
        upPwdFormData: {
          id: '',
          oldPassword: '',
          password: ''
        },
        upPwdFormItem: [
          {
            key: 'oldPassword',
            title: '旧密码'
          },
          {
            key: 'password',
            title: '新密码'
          }
        ],
        ruleUpPwdValidate: {
          oldPassword: [
            {required: false, message: '旧密码不能为空', trigger: 'blur'}
          ],
          password: [
            {required: true, message: '新密码不能为空', trigger: 'blur'},
            {pattern: '^(\\w){6,21}$', message: '密码必须6-21个字符之间', trigger: 'blur'},
            {validator: (rule, val, callback) => {
              if (this.upPwdFormData.oldPassword === val) {
                callback('新密码与旧密码不能一致');
              } else {
                callback();
              }
            }}
          ]
        },
        orgTree: []
      };
    },
    created () {
      // 初始化加载角色列表
      this.getRoleList();
      // 初始化加载机构树
      this.getOrgTree();
    },
    methods: {
      _getList () {
        // 作用合并搜索条件
        fetch.getList(Object.assign(this.searchData, this.searchObj)).then(this.callback);
      },
      getById (row) {
        fetch.getOne({userId: row.id}).then((result) => {
          this.modalFormItem[0].property.disabled = true;
          this.modalFormItem[1].property.disabled = true;
          this.modalFormData = result.data;
          this.modalFormData.password = ' ';
        });
      },
      clearFormValid () {
        this.$refs.form.resetFields();
        this.modalFormItem[0].property.disabled = false;
        this.modalFormItem[1].property.disabled = false;
        this.getOrgTree();
      },
      getOneData (data) {
        this.modalFormData = this._hyTool.deepCopy(data);
      },
      getRoleList () {
        // 获取用户角色列表
        roleService.getList({pageNum: 1, pageSize: 999}).then((result) => {
          let roleArray = this._hyTool.createSelectData(result.data.content, ['id', 'name']);
          this.modalFormItem[5].array = roleArray;
        });
      },
      getOrgTree () {
        // 获取机构树
        let opt = {id: 1};
        orgService.getTree(opt).then((result) => {
          // 展开父级节点
          this.$set(result.data, 'expand', true);
          this.orgTree = [result.data];
        });
      },
      editItem (row) {
        this.modalObj.title = '编辑';
        this.modalObj.addOrModify = true;
        this.clearFormValid();
        this.getById(row);
      },
      addOrUp (name) {
        this.$refs[name].validate(async (valid) => {
          if (valid) {
            this._hyTool.cal(true);
            // todo 密码加密
            if (this.modalObj.title === '新增') {
              await fetch.userSave(this.modalFormData);
              this.search();
            } else {
              let opt = {userId: this.modalFormData.id};
              await fetch.userUpdate(opt, this.modalFormData);
              this.search();
            }
            this.$Notice.success({title: this.modalObj.title + '成功'});
            this.modalObj.addOrModify = false;
            this._hyTool.cal(false);
          }
        });
      },
      deleteItem (row) {
        this.$Modal.confirm({
          title: '提示',
          content: '是否删除用户：' + row.username,
          onOk: () => {
            let payload = {userId: row.id};
            fetch.userDelete(payload).then((data) => {
              this.$Notice.success({title: '删除成功'});
              this.search();
            });
          }
        });
      },
      // 停用
      disableItem (row) {
        let status = null;
        let str = '';
        if (row.status === 1) {  // 正常
          status = 0;
          str = '禁用';
        } else if (row.status === 0) {  // 停用
          status = 1;
          str = '启用';
        }
        this.$Modal.confirm({
          title: '提示',
          content: '是否' + str + '用户：' + row.username,
          onOk: () => {
              let paramData = {
                userId: row.id,
                status: status
              };
              let operName;
              if (row.status === 1) {
                operName = '禁用';
              } else if (row.status === 0) {
                operName = '启用';
              }
              fetch.setStatus(paramData).then((data) => {
                this.$Notice.success({title: operName + '成功'});
                this.search();
              });
          }
        });
      },
      // 修改密码
      upPwdModal (row) {
        this.upPwdFormData.id = row.id;
        this.clearUpPwdFormValid();
        this.upPwdModalShow = true;
      },
      clearUpPwdFormValid () {
        this.$refs.upPwdForm.resetFields();
      },
      upPwd (name) {
        this.$refs[name].validate((valid) => {
          if (valid) {
            this._hyTool.cal(true);
            console.log(this.upPwdFormData);
            // todo 密码加密
            try {
              let opt = {userId: this.upPwdFormData.id};
              fetch.updatePassword(opt, this.upPwdFormData).then((data) => {
                this.$Notice.success({
                  title: '修改成功'
                });
                this.search();
              });
            } catch (e) {};
            this.upPwdModalShow = false;
            this._hyTool.cal(false);
          }
        });
      },
      handlerFocus () {
        // 获取父级节点文本框宽度
        let inputWidth = this.$refs.pId.$el.offsetWidth;
        // 设置树div宽度
        this.$refs.tree.style.width = inputWidth - 32 + 'px';
      },
      handleSelectTree (node) {
        console.log(node[0].id);
        this.modalFormData.orgName = node[0].title;
        this.modalFormData.orgId = node[0].id;
        this.$refs.form.validateField('orgName');
        // 验证
        this.showPoptip = false;
      }
    }
  };
</script>
